class socket {
	constructor(openid) { // 实例创建后就开始连接socket
		// return
		this.openid = openid;
		this.onload();
		this.time = null;
	}
	onload() {
		// console.log(`链接地址：---  wss://hxc.ctvig.com/websocket/${this.openid}`)
		let SocketTask = uni.connectSocket({
			url: `wss://hxc.ctvig.com/websocket/${this.openid}`,
			success: res => {
				console.log('连接成功', res);
			},
			fail: err => {
				if (this.time) clearInterval(this.time);
				console.log("连接报错", err)
			}
		});
		SocketTask.onOpen(msg => {
			if (this.time) clearInterval(this.time);
			console.log("连接打开事件，并且50秒内发送一次请求", msg);
			this.time = setInterval(() => {
				SocketTask.send({
					data: "ping",
					success: res => {
						console.log("向服务器发送内容成功");
					},
					fail: err => {
						console.log("向服务器发送内容失败");
					}
				})
			}, 50000);
		})
		SocketTask.onMessage(msg => {
			console.log('收到的消息', msg)

			if (msg.data == 'ping') return;
			uni.setStorageSync('msg_data', JSON.parse(msg.data));
			uni.navigateTo({
				url: "/commonPages/pay/index"
			})
		});
		SocketTask.onClose(msg => {
			if (this.time) clearInterval(this.time);
			console.log('关闭连接', msg);
			setTimeout(() => {
				this.onload(); //重新连接
			}, 500)
		})
		SocketTask.onError(msg => {
			if (this.time) clearInterval(this.time);
			console.log('连接出错', msg)
		})

	}
};
export const Socket = socket;
